package com.cpic.blood.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.cpic.blood.admin.service.ApiAllServie;
import com.cpic.blood.admin.service.impl.FileUploadService;
import com.cpic.blood.core.common.R;
import com.cpic.blood.core.utils.HttpClientUtils;
import com.cpic.blood.core.vo.HiveFileConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController {

    @Autowired
    private ApiAllServie apiAllServie;

    @Autowired
    private FileUploadService fileUploadService;

    @RequestMapping(value = "/getHiveFileOutTxt", method = {RequestMethod.GET, RequestMethod.POST})
    public R getHiveFileOutTxt() {
        try {
            apiAllServie.startHiveFileJob();
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error();
        }
        return R.success();
    }

    @RequestMapping(value = "/hello", method = {RequestMethod.GET, RequestMethod.POST})
    public R hello() {
        try {
            System.out.println("hello world");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error("失败");
        }
        return R.success("成功");
    }

    @RequestMapping(value = "/testHttpClient", method = RequestMethod.POST)
    public R httpClientTest(@RequestBody HiveFileConfigVo hiveFileConfigVo){
        System.out.println("httpClientTest执行...");
        return R.success(hiveFileConfigVo);
    }

    @RequestMapping(value = "/testHttpResponse", method = RequestMethod.GET)
    public R testHttpResponse(){
        HiveFileConfigVo hiveFileConfigVo = new HiveFileConfigVo();
        hiveFileConfigVo.setFileName("config.properties");
        hiveFileConfigVo.setHiveSql("hive SQL");
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hiveFileConfigVo);
        String result = HttpClientUtils.sendPost("http://localhost:8080/blood-analysis/api/testHttpClient", jsonObject);
        return R.success(result);
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String fileUrl = fileUploadService.uploadFile(file);
        return "File uploaded successfully. URL: " + fileUrl;
    }
}
